<template>
  <div class="progress" style="---color: #ff4e4e">
    <div class="progress-rail" @click="click" ref="progress_rail_ref"></div>
    <div
      class="progress-track"
      @click="click"
      :style="{ width: `${value}%` }"
    ></div>
    <div
      class="progress-thumb"
      :style="{ left: `${value}%` }"
      @mousedown="dragStart"
      ref="thumb"
    ></div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Number,
      default: 0,
    },
    min: {
      type: Number,
      default: 0,
    },
    max: {
      type: Number,
      default: 100,
    },
  },
  mounted() {
    this.rail = this.$refs.progress_rail_ref;
    this.thumb = this.$refs.thumb;
  },
  data() {
    return {
      currentValue: 0,
      rail: null,
      thumb: null,
    };
  },
  methods: {
    dragStart(event) {
      document.addEventListener("mousedown", this.mousdDown);
      document.addEventListener("mouseup", this.mousdUp);
    },
    removeDocumentEvent() {
      document.removeEventListener("mousedown", this.mousdDown);
      document.removeEventListener("mouseup", this.mousdUp);
      document.removeEventListener("mousemove", this.mouseMove);
    },
    mousdDown() {
      console.log("start");
      document.addEventListener("mousemove", this.mouseMove);
    },
    mousdUp() {
      console.log("end");
      this.removeDocumentEvent();
      this.$emit("input", this.currentValue);
    },
    mouseMove(e) {
      const value =
        (e.clientX - this.thumb.clientWidth) / this.rail.clientWidth;

      this.rangeValue = this.computeRangeValue(value);
    },
    click(e) {
      const value =
        (e.clientX - this.thumb.clientWidth) / this.rail.clientWidth;
      this.rangeValue = this.computeRangeValue(value);
    },
    computeRangeValue(value) {
      if (value <= 0) {
        return 0;
      } else if (value >= 1) {
        return 1;
      }
      return value;
    },
  },
  computed: {
    rangeValue: {
      get() {
        return this.value;
      },
      set(value) {
        this.currentValue = (this.max - this.min) * value;
        this.$emit("input", this.currentValue);
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.progress {
  height: 4px;
  position: relative;
  * {
    box-sizing: border-box;
    cursor: pointer;
  }
  &-rail {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
  }
  &-track {
    pointer-events: none;
    position: absolute;
    height: 100%;
    left: 0;
    right: auto;
    width: 80%;
    background-color: var(---color);
  }
  &-thumb {
    position: absolute;
    left: 80%;
    height: 14px;
    width: 14px;
    margin-top: -5px;
    background-color: #fff;
    border: 2px solid var(---color);
    border-radius: 50%;
  }
}
</style>